package com.wyg.server;

import com.wyg.coder.RPCDecoder;
import com.wyg.coder.RPCEncoder;
import com.wyg.protocol.RPCRequest;
import com.wyg.protocol.RPCResponse;
import com.wyg.service.UserService;
import com.wyg.service.impl.UserServiceImpl;
import com.wyg.zookeeper.Constant;
import com.wyg.zookeeper.ServiceRegistry;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: WYG
 * @time: 2020/10/24 17:31
 */

public class RPCServer {
    private Map<String, Object> getService() {
        Map<String, Object> services = new HashMap<String, Object>();
        services.put(UserService.class.getName(), new UserServiceImpl());
        return services;
    }

    private void bind(int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Map<String, Object> handlerMap = getService();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new LengthFieldBasedFrameDecoder(65535,0,2,0,2));
                            pipeline.addLast(new RPCDecoder(RPCRequest.class));
                            pipeline.addLast(new LengthFieldPrepender(2));
                            pipeline.addLast(new RPCEncoder(RPCResponse.class));
                            pipeline.addLast(new RPCServerHandler(handlerMap));
                        }
                    });
            ChannelFuture future = serverBootstrap.bind(port).sync();
            System.out.println("服务提供方开始提供服务");
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static String getAddress() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return address.getHostAddress();
    }

    public void initService(int port) {
        ServiceRegistry serviceRegistry = new ServiceRegistry();
        String ip = getAddress();
//      向zookeeper注册服务地址
        serviceRegistry.register(ip + Constant.ZK_IP_SPLIT + port);
        bind(port);
    }

    public static void main(String[] args) {
        int port = 8888;
        new RPCServer().initService(port);
    }
}
